<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\manager\StoreAppMgr;
use app\common\model\Store;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAlarm;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\utils\enum\AlarmState;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\OrdersType;
use support\Request;
use think\facade\Cache;
use think\facade\Config;

/**
 * 默认首页
 *
 * @author 贵州猿创科技有限公司
 * @Email 416716328@qq.com
 * @DateTime 2023-03-07
 */
class IndexController extends BaseController {
    /**
     * 无需验证APPID方法
     * @var array
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $noNeedAppid = ['index'];

    /**
     * 无需登录方法
     * @var array
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $noNeedLogin = ['index'];

    /**
     * 无需鉴权方法
     * @var array
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $noNeedAuth = ['index'];

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize() {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }

    /**
     * 渲染后台
     * @param \support\Request $request
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function index(Request $request) {
        return getAdminView($request->plugin);
    }
    public function statistic(Request $request) {
        $team       = [];
        try {
            $StoreApp = StoreAppMgr::model(['id' => $request->saas_appid]);
            $store    = Store::where(['id' => $StoreApp->store_id])->find()->toArray();
            # 设置系统默认版权
            $copyright_name     = (string) getHpConfig('store_copyright_name');
            $copyright_service  = (string) getHpConfig('store_copyright_service');
            $copyright_tutorial = (string) getHpConfig('store_copyright_tutorial');
            $tutorial           = '';
            if ($copyright_tutorial) {
                $tutorial = $this->getTutorial((string) $copyright_tutorial);
            }

            if (!empty($store['title']) && !empty($store['copyright_service']) && !empty($store['copyright_tutorial'])) {
                $copyright_name    = $store['title'];
                $copyright_service = $store['copyright_service'];
                $tutorial          = $this->getTutorial((string) $store['copyright_tutorial']);
            }
            $teamInfo   = [
                'about_name' => $copyright_name,
                'ecology' => $tutorial,
                'service_wx' => $copyright_service,
            ];
            $teamFields = [
                'about_name' => '版权信息',
                'ecology' => '系统教程',
                'service_wx' => '专属客服',
            ];
            foreach ($teamFields as $field => $label) {
                $team[] = [
                    'title' => $label,
                    'values' => $teamInfo[$field],
                ];
            }
        } catch (\Throwable $th) {
        }
        // 获取产品动态
        $product = [];
        $echarts = Cache::get('Massage.statistic.admin.echarts.' . $request->saas_appid);
        $echarts = json_decode($echarts);

        $orderState = [
            OrdersState::PAY['value'],
            OrdersState::WAIT_START['value'],
            OrdersState::SERVICE_ING['value'],
            OrdersState::WAIT_COMMENT['value'],
            OrdersState::FINISH['value'],
        ];
        if (!$echarts) {
            $series = [
                'name' => '',
                'type' => 'line',
                'stack' => 'Total',
                'smooth' => true,
                'data' => [],
            ];
            $echarts = [
                'legend' => [
                    'data' => ['用户', '订单', '会员订单', '订单(金额)']
                ],
                'xAxis' => [
                    'data' => []
                ],
                'series' => []
            ];
            $userNum = [];
            $orderNum = [];
            $serviceOrderNum = [];
            $orderPrice = [];
            for ($i = 7; $i > 0; $i--) {
                $time = strtotime("-{$i} day");
                $whereDay = date('Y-m-d', $time);
                $date = date('m-d', $time);
                $echarts['xAxis']['data'][] = $date;
                $userNum[] = MassageUser::where(['saas_appid' => $request->saas_appid])->whereDay('create_time', $whereDay)->count('id');
                $serviceOrderNum[] = MassageOrders::where(['saas_appid' => $request->saas_appid, 'orders_type' => OrdersType::RESERVATION['value'], 'state' => $orderState])->whereDay('create_time', $whereDay)->count('id');
                $orderNum[] = MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => $orderState])->whereDay('create_time', $whereDay)->count('id');
                $orderPrice[] = MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => $orderState])->whereDay('create_time', $whereDay)->sum('price');
            }
            $series['name'] = '用户';
            $series['data'] = $userNum;
            $echarts['series'][] = $series;
            $series['name'] = '订单';
            $series['data'] = $orderNum;
            $echarts['series'][] = $series;
            $series['name'] = '服务订单';
            $series['data'] = $serviceOrderNum;
            $echarts['series'][] = $series;
            $series['name'] = '订单(金额)';
            $series['data'] = $orderPrice;
            $echarts['series'][] = $series;
            $ex = strtotime('23:59:59') - time();
            Cache::set('Massage.statistic.admin.echarts.' . $request->saas_appid, json_encode($echarts, JSON_UNESCAPED_UNICODE), $ex);
        }
        $statistic = [
            'userNum' => MassageUser::where(['saas_appid' => $request->saas_appid])->whereDay('create_time')->count('id'),
            'orderNum' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => $orderState])->whereDay('create_time')->count('id'),
            'serviceOrderNum' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'orders_type' => OrdersType::RESERVATION['value'], 'state' => $orderState])->whereDay('create_time')->count('id'),
            'orderPrice' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => $orderState])->whereDay('create_time')->sum('price'),
            'alarm' => MassageAlarm::where(['saas_appid' => $request->saas_appid, 'state' => AlarmState::WAIT['value']])->count()
        ];
        $order = [
            'complete' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => OrdersState::FINISH['value']])->whereDay('create_time')->count('id'),
            'pay' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => OrdersState::PAY['value']])->whereDay('create_time')->count('id'),
            'nopay' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => OrdersState::NOT_PAY['value']])->whereDay('create_time')->count('id'),
            'turnover' => MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => $orderState])->whereDay('create_time')->sum('price'),
        ];
        $data = [
            'team'             => $team,
            'product'          => $product,
            'echarts'          =>  $echarts,
            'statistic'         => $statistic,
            'order' => $order
        ];
        return $this->successRes($data);
    }

    /**
     * 获取系统教程
     * @param mixed $tutorial
     * @return string
     * @author John
     */
    private function getTutorial(string $tutorialConfig): string {
        $tutorialArray = explode("\n", $tutorialConfig);
        $tutorial      = '';
        if ($tutorialConfig) {
            $tutorialArr = [];
            foreach ($tutorialArray as $value) {
                $item = explode('|', $value);
                if (count($item) < 2) {
                    continue;
                }
                $tutorialArr[] = "<a href='{$item[1]}' target='_blank'>{$item[0]}</a>";
            }
            $tutorial = implode('，', $tutorialArr);
        }
        return $tutorial;
    }

    public function orders(Request $request) {
        $orders_num = MassageOrders::where(['saas_appid' => $request->appid, 'state' => OrdersState::WAIT_START['value']])->count('id');
        $last_order = MassageOrders::where(['saas_appid' => $request->appid, 'state' => OrdersState::WAIT_START['value']])->order('id', 'desc')->find();
        return $this->successRes(['orders_num' => $orders_num, 'last_order' => $last_order ? $last_order['id'] : '']);
    }
}
